package cs757;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.Vector;

import javax.swing.*;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.border.EmptyBorder;

public class DlgEditProject extends JDialog {


	private static final long serialVersionUID = -7533448602147257767L;
	
	private final JPanel contentPanel = new JPanel();
	private JTextField textFieldFunding;
	
	//Database connection
	private DatabaseConnector conn;
	
	//Key for the project record that we will be modifying
	private String recordID;
	
	private DefaultListModel studentListModel = new DefaultListModel();
	private DefaultListModel professorListModel = new DefaultListModel();

	
	private boolean ok = false;
	private JList listStudents;
	private JList listProfessors;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		try {
			DlgEditProject dialog = new DlgEditProject();
			dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
			dialog.setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Create the dialog.
	 */
	public DlgEditProject() {
		setTitle("Edit Project");
		setBounds(100, 100, 389, 418);
		getContentPane().setLayout(new BorderLayout());
		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(contentPanel, BorderLayout.CENTER);
		JLabel lblFunding = new JLabel("Funding:");
		textFieldFunding = new JTextField();
		textFieldFunding.setColumns(10);
		JLabel lblStudents = new JLabel("Project Students:");
		
		JButton btnAddStudent = new JButton("Add");
		btnAddStudent.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				DlgAddStudentToProject addStudent = new DlgAddStudentToProject();
				addStudent.setModal(true);
				addStudent.setConn(conn);
				addStudent.setList(studentListModel);
				addStudent.setRecordID(recordID);
				addStudent.populateProfessorComboBox();
				addStudent.populateStudentComboBox();
				boolean okToShow = addStudent.checkIfSponsorsAvailable();
				if (okToShow){
					addStudent.setVisible(true);
				}
			}
		});
		
		JButton btnDeleteStudent = new JButton("Delete");
		btnDeleteStudent.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if (listStudents.getSelectedIndex() >= 0){
					try {  
						String student = listStudents.getSelectedValue().toString();
						String recordKey = student.substring(0, student.indexOf('-'));

						conn.executeDelete(DatabaseConnector.DELETE_GROUP_MEMBER_STUDENT_QUERY, recordKey);

						studentListModel.clear();
						populateStudentList();
					} catch (SQLException e) {
						JOptionPane.showMessageDialog(null, "Error deleting from database.\nQuery:"+DatabaseConnector.DELETE_GROUP_MEMBER_STUDENT_QUERY,
								"Error In Query", JOptionPane.ERROR_MESSAGE);
					}
				}
				else {
					JOptionPane.showMessageDialog(null, "Please select a person from the list",
							"No selection", JOptionPane.INFORMATION_MESSAGE);
				}
			}
		});
		
		JScrollPane scrollPane = new JScrollPane();
		
		JScrollPane scrollPane_1 = new JScrollPane();
		
		JLabel lblProfessors = new JLabel("Project Professors:");
		
		JButton btnAddProfessor = new JButton("Add");
		btnAddProfessor.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				DlgAddProfessorToProject addProfessor = new DlgAddProfessorToProject();
				addProfessor.setModal(true);
				addProfessor.setConn(conn);
				addProfessor.setList(professorListModel);
				addProfessor.setRecordID(recordID);
				addProfessor.populateProfessorComboBox();
				addProfessor.setVisible(true);
			}
		});
		
		JButton buttonDeleteProfessor = new JButton("Delete");
		buttonDeleteProfessor.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if (listProfessors.getSelectedIndex() >= 0){
					try {  
						String professor = listProfessors.getSelectedValue().toString();
						String recordKey = professor.substring(0, professor.indexOf('-'));
						
						conn.executeDelete(DatabaseConnector.DELETE_GROUP_MEMBER_PROFESSOR_QUERY, recordKey);
	
						professorListModel.clear();
						populateProfessorList();
					} catch (SQLException e) {
						JOptionPane.showMessageDialog(null, "Error deleting from database.\nQuery:"+DatabaseConnector.DELETE_GROUP_MEMBER_PROFESSOR_QUERY,
								"Error In Query", JOptionPane.ERROR_MESSAGE);
					}
				}
				else {
					JOptionPane.showMessageDialog(null, "Please select a person from the list",
							"No selection", JOptionPane.INFORMATION_MESSAGE);
				}
			}
		});
		GroupLayout gl_contentPanel = new GroupLayout(contentPanel);
		gl_contentPanel.setHorizontalGroup(
			gl_contentPanel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_contentPanel.createSequentialGroup()
					.addContainerGap()
					.addGroup(gl_contentPanel.createParallelGroup(Alignment.LEADING)
						.addGroup(gl_contentPanel.createSequentialGroup()
							.addGroup(gl_contentPanel.createParallelGroup(Alignment.LEADING)
								.addGroup(gl_contentPanel.createSequentialGroup()
									.addComponent(scrollPane_1, GroupLayout.PREFERRED_SIZE, 223, GroupLayout.PREFERRED_SIZE)
									.addPreferredGap(ComponentPlacement.RELATED)
									.addGroup(gl_contentPanel.createParallelGroup(Alignment.LEADING)
										.addComponent(buttonDeleteProfessor, GroupLayout.DEFAULT_SIZE, 63, Short.MAX_VALUE)
										.addComponent(btnAddProfessor, GroupLayout.DEFAULT_SIZE, 63, Short.MAX_VALUE)))
								.addGroup(gl_contentPanel.createSequentialGroup()
									.addComponent(lblFunding)
									.addPreferredGap(ComponentPlacement.RELATED)
									.addComponent(textFieldFunding, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
								.addComponent(lblStudents)
								.addGroup(gl_contentPanel.createSequentialGroup()
									.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 223, GroupLayout.PREFERRED_SIZE)
									.addPreferredGap(ComponentPlacement.RELATED)
									.addGroup(gl_contentPanel.createParallelGroup(Alignment.LEADING)
										.addComponent(btnDeleteStudent, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
										.addComponent(btnAddStudent, GroupLayout.DEFAULT_SIZE, 63, Short.MAX_VALUE))))
							.addGap(208))
						.addGroup(gl_contentPanel.createSequentialGroup()
							.addComponent(lblProfessors)
							.addContainerGap(269, Short.MAX_VALUE))))
		);
		gl_contentPanel.setVerticalGroup(
			gl_contentPanel.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_contentPanel.createSequentialGroup()
					.addContainerGap()
					.addGroup(gl_contentPanel.createParallelGroup(Alignment.TRAILING)
						.addGroup(gl_contentPanel.createSequentialGroup()
							.addComponent(btnAddStudent, GroupLayout.PREFERRED_SIZE, 39, GroupLayout.PREFERRED_SIZE)
							.addPreferredGap(ComponentPlacement.RELATED)
							.addComponent(btnDeleteStudent, GroupLayout.PREFERRED_SIZE, 41, GroupLayout.PREFERRED_SIZE)
							.addGap(12))
						.addGroup(gl_contentPanel.createSequentialGroup()
							.addGroup(gl_contentPanel.createParallelGroup(Alignment.BASELINE)
								.addComponent(lblFunding)
								.addComponent(textFieldFunding, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
							.addPreferredGap(ComponentPlacement.RELATED)
							.addComponent(lblStudents)
							.addPreferredGap(ComponentPlacement.RELATED)
							.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 116, GroupLayout.PREFERRED_SIZE)))
					.addGap(0)
					.addGroup(gl_contentPanel.createParallelGroup(Alignment.LEADING)
						.addGroup(gl_contentPanel.createSequentialGroup()
							.addGap(11)
							.addComponent(lblProfessors)
							.addGap(7)
							.addComponent(scrollPane_1, 0, 0, Short.MAX_VALUE))
						.addGroup(gl_contentPanel.createSequentialGroup()
							.addGap(51)
							.addComponent(btnAddProfessor, GroupLayout.PREFERRED_SIZE, 40, GroupLayout.PREFERRED_SIZE)
							.addPreferredGap(ComponentPlacement.RELATED)
							.addComponent(buttonDeleteProfessor, GroupLayout.PREFERRED_SIZE, 41, GroupLayout.PREFERRED_SIZE)))
					.addContainerGap())
		);
		
		listProfessors = new JList(professorListModel);
		scrollPane_1.setViewportView(listProfessors);
		
		listStudents = new JList(studentListModel);
		scrollPane.setViewportView(listStudents);
		contentPanel.setLayout(gl_contentPanel);
		{
			JPanel buttonPane = new JPanel();
			buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
			getContentPane().add(buttonPane, BorderLayout.SOUTH);
			{
				JButton okButton = new JButton("OK");
				okButton.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						try {
							editRecord();
							ok = true;
							closeDialog();
						} catch (SQLException e1) {
							JOptionPane.showMessageDialog(null, "Error inserting into database.\n Please check all fields for valid values.",
									"Error In Insert", JOptionPane.ERROR_MESSAGE);
						}
						 catch (NumberFormatException e2) {
								JOptionPane.showMessageDialog(null, "Error inserting into database.\n You appear to have entered non-integer values in integer fields.",
										"Error In Insert", JOptionPane.ERROR_MESSAGE);
						}
					}
				});
				okButton.setActionCommand("OK");
				buttonPane.add(okButton);
				getRootPane().setDefaultButton(okButton);
			}
		}
	}
	
	/**
	 * Gather the needed data from the dialog, and use the DatabaseConnector to execute an update statement
	 * 
	 * Update the record for this project with the new funding amount
	 * @throws SQLException
	 * @throws NumberFormatException
	 */
	private void editRecord() throws SQLException{
		conn.executeUpdate(DatabaseConnector.UPDATE_QUERY, DatabaseConnector.UPDATE_QUERY_WHERE, 
				textFieldFunding.getText(), recordID);
	}
	
	/**
	 * Query the DB for the list of students and use the list to populate the students list box
	 */
	protected void populateStudentList(){
		try {
			Vector<Vector<Object>> results = conn.executeQuery(DatabaseConnector.STUDENT_WORKS_QUERY+recordID, 2);
			
			for(Vector<Object> row:results){
				studentListModel.addElement(row.get(0)+" - "+row.get(1));
			}
		} catch (SQLException e) {
			JOptionPane.showMessageDialog(null, "Error querying major IDs from department table.\n ",
					"Error In Query", JOptionPane.ERROR_MESSAGE);
		}
	}
	
	/**
	 * Query the DB for the list of professors and use the list to populate the professors list box
	 */
	protected void populateProfessorList(){
		try {
			Vector<Vector<Object>> results = conn.executeQuery(DatabaseConnector.PROFESSOR_WORKS_QUERY+recordID, 2);
			
			for(Vector<Object> row:results){
				professorListModel.addElement(row.get(0)+" - "+row.get(1));
			}
		} catch (SQLException e) {
			JOptionPane.showMessageDialog(null, "Error querying major IDs from department table.\n ",
					"Error In Query", JOptionPane.ERROR_MESSAGE);
		}
	}

	/**
	 * Close the edit project GUI
	 */
	private void closeDialog(){
		this.setVisible(false);
	}

	/**
	 * @return the ok
	 */
	public boolean isOk() {
		return ok;
	}

	/**
	 * @param conn the conn to set
	 */
	public void setConn(DatabaseConnector conn) {
		this.conn = conn;
	}
	
	/**
	 * @param recordID the recordID to set
	 */
	public void setRecordID(String recordID) {
		this.recordID = recordID;
	}
	
	/**
	 * Set the funding text field value
	 * @param value
	 */
	public void setTextFieldFundingValue(String value){
		textFieldFunding.setText(value);
	}
}
